

from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.forms import ModelForm
from django.shortcuts import render, redirect
from django import forms
from django.utils.safestring import mark_safe

from app01 import models
from app01.models import Department
from app01.utils.pagination import Pagination
from app01.utils.bootstrap import BootstrapModelForm


# def user_list(request):
#     """用户列表"""
#     user_list = models.UserInfo.objects.all()
#
#     print(user_list)
#     return render(request, "user_list.html", {"user_list": user_list})


def user_list(request):
    """用户列表"""
    # 获取所有用户列表
    user_list = models.UserInfo.objects.all()

    page_object = Pagination(request, user_list, page_size=10 )

    # 用 python 的语法获取数据
    """
    for obj in user_data:
        # obj.get_gender_display() 表示匹配 男/女,原始字段名为gender,obj.get_字段名称_display()
        # obj.create_time.strftime("%Y-%m-%d") 表示将时间格式转换成固定格式的字符串
        # obj.depart.title 表示获取depart_id对应的部门名称,因为我们在models中定义表时与另外一张表设置了级联关系,有外键
        print(obj.id, obj.name, obj.password, obj.age, obj.account, obj.get_gender_display(), obj.depart.title, obj.create_time.strftime("%Y-%m-%d"))
    """

    page_object.html()

    context = {
        "user_list": page_object.page_queryset,
        "page_string": page_object.page_string,
    }

    return render(request, "user_list.html", context)








class UserModelForm(BootstrapModelForm):
    class Meta:

            model = models.UserInfo
            fields = ['name', 'password','age','sex','create_time','account','depart']

# class UserModelForm(forms.ModelForm):
#     class Meta:
#         model = models.UserInfo
#         fields = ['name', 'password','age','sex','create_time','account','depart']
#         #插件
#         # widgets = {
#         # "name": forms.TextInput(attrs={"class": "form-control", "placeholder": ""})
#         # }
#
#         #使用BootstrapModelForm类,可以自动生成form表单的样式
#     # def __init__(self, *args, **kwargs):
#     #     super().__init__(*args, **kwargs)
#     #     for name,field in self.fields.items():
#     #         field.widget.attrs={"class" :"form-control"}

def user_add1(request):
    """用户添加"""
    if request.method == "GET":
        form=UserModelForm()
        return render(request, "user_add1.html",{"form":form})

    #数据效验
    # form=UserModelForm(request.POST)
    # if form.is_valid():
    #     form.save()
    # else:print(form.errors)
    #
    # return redirect("/user/list/")
    form = UserModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")  # 保存成功后重定向到用户列表页
    else:
        if not request.POST.get('username') or not request.POST.get('email'):
            # 如果用户名或邮箱为空，向用户提供操作提示
            message = "用户名和邮箱不能为空"
        else:
            message = "数据校验失败，请检查输入"
        print(message)  # 在控制台打印提示信息，也可以使用日志记录模块记录到日志文件中

        # 渲染表单页面，并将错误信息传递给模板以便显示
        return render(request, "user_add1.html", {"form": form, "message": message})




def user_add(request):
    """用户添加"""
    context={
        "gender_list":((1,"男"),(2,"女")),
        "depart_list" : models.Department.objects.all()
    }
    if request.method == "GET":


        return render(request, "user_add.html",context)
        #return render(request, "user_add.html",{"form":form})


    if request.method == "POST":
        name = request.POST.get("name")
        password = request.POST.get("password")
        gender = request.POST.get("gender")
        age = request.POST.get("age")
        depart_id = request.POST.get("department")
        create_time=request.POST.get("create_time")
        account = request.POST.get("account")
        models.UserInfo.objects.create(name=name,password=password,sex=gender,depart_id=depart_id,age=age,create_time=create_time,account=account)


    return redirect("/user/list/")












def user_edit(request,id):
    """用户编辑"""
    row_object=models.UserInfo.objects.filter(id=id).first()
    if request.method == "GET":


        form = UserModelForm(instance=row_object)



        return render(request, "user_edit.html",{"id":id,"form":form})



    form=UserModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    else:
        print(form.errors)
        return render("user_edit.html", {"form":form})







def user_del(request):
    """用户删除"""
    if request.method == 'GET':
        nid=request.GET.get("nid")
        models.UserInfo.objects.filter(id=nid).delete()
        return redirect("/user/list/")




